package com.white.commonlib.engine.img;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * Created by yutf on 2017/6/7 0007.
 */

public class GlideRoundTransform extends BitmapTransformation
{

    private float leftTopR, rightTop, leftBottomR, rightBottomR;
    private float radius;
    /**只有底部圆角*/
    public static final int TYPE_BOTTOM_ONLY = 1;
    /**只有顶部圆角*/
    public static final int TYPE_TOP_ONLY = 2;
    /**全部圆角*/
    public static final int TYPE_ROUND_ALL = 3;
    private int roundType;

    public GlideRoundTransform(Context context)
    {
        this(context, 5, TYPE_ROUND_ALL);
    }

    public GlideRoundTransform(Context context, int dp, int roundType)
    {
        super(context);
        radius = context.getResources().getDisplayMetrics().density * dp;
        this.roundType = roundType;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight)
    {
        return roundCrop(pool, toTransform);
    }

    private Bitmap roundCrop(BitmapPool pool, Bitmap source)
    {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null)
        {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        switch (roundType)
        {
            case TYPE_BOTTOM_ONLY:
                float border = source.getHeight()- 2 * radius;
                canvas.drawRect(new RectF(0, 0, source.getWidth(), border), paint);
                canvas.drawRoundRect(new RectF(0, border, source.getWidth(), source.getHeight()), radius, radius, paint);
                break;
            case TYPE_TOP_ONLY:
                canvas.drawRoundRect(new RectF(0, 0, source.getWidth(), 2 * radius), radius, radius, paint);
                canvas.drawRect(new RectF(0, 2 * radius, source.getWidth(), source.getHeight()), paint);
                break;
            default:
                canvas.drawRoundRect(new RectF(0, 0, source.getWidth(), source.getHeight()), radius, radius, paint);
                break;
        }
        return result;
    }

    @Override
    public String getId()
    {
        return getClass().getName() + Math.round(radius);
    }
}

